import { Model, DataTypes, Optional, Sequelize } from 'sequelize';

// 角色属性接口
interface RoleAttributes {
  id: string;
  name: string;
  code: string;
  description: string;
  is_system: boolean;
  created_at: Date;
  updated_at: Date;
  deleted_at?: Date;
}

// 创建时可选的属性
interface RoleCreationAttributes extends Optional<RoleAttributes, 'id' | 'created_at' | 'updated_at'> {}

/**
 * 角色模型
 * @description 系统角色模型，用于RBAC权限控制
 */
class Role extends Model<RoleAttributes, RoleCreationAttributes> implements RoleAttributes {
  public id!: string;
  public name!: string;
  public code!: string;
  public description!: string;
  public is_system!: boolean;
  public created_at!: Date;
  public updated_at!: Date;
  public deleted_at?: Date;

  // 用于TypeScript的类型声明，表示关联关系
  public readonly permissions?: any[];
  public readonly users?: any[];

  // 静态初始化方法
  public static initialize(sequelize: Sequelize): void {
    Role.init(
      {
        id: {
          type: DataTypes.UUID,
          defaultValue: DataTypes.UUIDV4,
          primaryKey: true,
        },
        name: {
          type: DataTypes.STRING(50),
          allowNull: false,
          comment: '角色名称',
        },
        code: {
          type: DataTypes.STRING(50),
          allowNull: false,
          unique: true,
          comment: '角色编码，唯一标识',
        },
        description: {
          type: DataTypes.STRING(200),
          allowNull: true,
          comment: '角色描述',
        },
        is_system: {
          type: DataTypes.BOOLEAN,
          allowNull: false,
          defaultValue: false,
          comment: '是否为系统内置角色，内置角色不允许删除',
        },
        created_at: {
          type: DataTypes.DATE,
          allowNull: false,
          defaultValue: DataTypes.NOW,
        },
        updated_at: {
          type: DataTypes.DATE,
          allowNull: false,
          defaultValue: DataTypes.NOW,
        },
        deleted_at: {
          type: DataTypes.DATE,
          allowNull: true,
        },
      },
      {
        sequelize,
        tableName: 'roles',
        timestamps: true,
        createdAt: 'created_at',
        updatedAt: 'updated_at',
        deletedAt: 'deleted_at',
        paranoid: true, // 启用软删除
        indexes: [
          {
            name: 'roles_code_index',
            unique: true,
            fields: ['code'],
          },
        ],
      }
    );
  }

  // 定义关联关系
  public static associate(models: any): void {
    // 角色与权限多对多关系
    Role.belongsToMany(models.Permission, {
      through: 'role_permissions',
      foreignKey: 'role_id',
      otherKey: 'permission_id',
      as: 'permissions',
    });

    // 角色与用户多对多关系
    Role.belongsToMany(models.User, {
      through: 'user_roles',
      foreignKey: 'role_id',
      otherKey: 'user_id',
      as: 'users',
    });
  }

  /**
   * 创建系统默认角色
   */
  public static async createDefaultRoles(): Promise<void> {
    const defaultRoles = [
      {
        name: '超级管理员',
        code: 'admin',
        description: '系统超级管理员，拥有所有权限',
        is_system: true,
      },
      {
        name: '编辑',
        code: 'editor',
        description: '内容编辑人员，拥有内容管理相关权限',
        is_system: true,
      },
      {
        name: '访客',
        code: 'visitor',
        description: '系统访客，拥有只读权限',
        is_system: true,
      },
    ];

    // 使用事务保证数据一致性
    const transaction = await Role.sequelize!.transaction();

    try {
      for (const role of defaultRoles) {
        await Role.findOrCreate({
          where: { code: role.code },
          defaults: role,
          transaction,
        });
      }

      await transaction.commit();
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }
}

export default Role; 